﻿using System;
using Transformable_Engine_v2.Engine.Animation.Trajectory;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Transformable_Engine_v2.Engine.Animation.ScaleAnimation
{
    public class ScaleAnimation : BaseAnimation
    {
        public IScaleAnimatable AffectedObject { private get; set; }
        private readonly ITrajectory _trajectory;

        private TE_Vector2 _beginScale;
        private TE_Vector2 _currentScale;
        private readonly TE_Vector2 _endScale;

        public override void Update(TimeSpan gameTime)
        {
            
        }

        public override void FixedStepUpdate(TimeSpan gameTime)
        {
            if(IsAlive() && IsStarted)
            {
                double percentage = _trajectory.GetPercentageProgression(DurationTimer.PercentageElapsed);
                TE_Vector2 nextScale = (_endScale - _beginScale) * percentage + _beginScale;
                AffectedObject.AddToScale(nextScale - _currentScale);
                _currentScale = nextScale;
            }

            base.FixedStepUpdate(gameTime);
        }

        protected override void DelayEnd()
        {
            _beginScale = AffectedObject.GetScale();

            _currentScale = _beginScale;

            Log.LogDebug(this.ToString());

            base.DelayEnd();
        }

        public override string ToString()
        {
            return string.Format("Scale from {0} to {1}", _beginScale, _endScale);
        }

        protected override void DurationEnd()
        {
            if (!IsLooping)
            {
                AffectedObject.AddToScale(_endScale - _currentScale);
                _currentScale = _endScale;
            }

            base.DurationEnd();
            
        }

        public ScaleAnimation(ITrajectory trajectory, TE_Vector2 targetScale,
                                    double duration, bool isLooping, double delay, bool autoStart = true)
            : base(duration, isLooping, delay, autoStart)
        {
            _trajectory = trajectory;

            _endScale = targetScale;
        }

        public override void Die()
        {
            AffectedObject = null;
            base.Die();
        }

    }
}